<template>
  <div class="import-file">
    <input class="import-file__input" type="file" @change="handleChange">
    <el-button class="import-file__button " type="primary">上传<i class="el-icon-upload el-icon--right "></i></el-button>
  </div>
</template>

<script>
//  参考文档 http://blog.haoji.me/js-excel.html#huo-qu-workbook-dui-xiang
import * as XLSX from 'xlsx';
// 读取本地excel文件
function readWorkbookFromLocalFile(file, callback) {
  var reader = new FileReader();
  reader.onload = function (e) {
    var data = e.target.result;
    var workbook = XLSX.read(data, { type: 'binary' });
    if (callback) callback(workbook);
  };
  reader.readAsBinaryString(file);
}

function outputWorkbook(workbook) {
  var sheetNames = workbook.SheetNames; // 工作表名称集合
  let res = []
  sheetNames.forEach(name => {
    var worksheet = workbook.Sheets[name]; // 只能通过工作表名称来获取指定工作表
    let temp = XLSX.utils.sheet_to_json(worksheet)
    res.push({ [name]: temp })
  })
  return res
}
export default {

  methods: {
    handleChange(e) {
      let file = e.target.files[0]
      file && readWorkbookFromLocalFile(file, (workbook) => {
        let arr = outputWorkbook(workbook)
        console.log(arr);
        this.$emit("ImportExcelSuccess", arr)
      })
    },

  }
}
</script>

<style lang="less" scoped>
.import-file {
  position: relative;
  width: 80px;
  height: 40px;

  &__input,
  &__button {
    display: inline-block;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;

    &:hover {
      cursor: pointer;
    }
  }

  &__input {
    opacity: 0;
  }

  &__button {
    z-index: 1;
  }


}
</style>


